import json
import pickle

from django.http import HttpResponse
import random
from redis import StrictRedis

redis = StrictRedis(host='localhost', port=6379, db=0, password=None)


class progress(object):
    def __init__(self, id, a, b, c, need_time):
        self.id = id
        self.status = "W"
        self.a = a
        self.b = b
        self.c = c
        self.need_time = need_time
        self.get_time = 0


def proinit(request):  # 初始化
    if request.method == 'POST':
        concat = request.POST
        try:
            a = int(concat["a_num"])
            b = int(concat["b_num"])
            c = int(concat["c_num"])
            initnum = int(concat["initnum"])
        except:
            a = 10
            b = 10
            c = 10
            initnum = 3
        for elem in redis.keys():  # 清空redis
            redis.delete(elem)
        redis.set("a", a)
        redis.set("b", b)
        redis.set("c", c)
        ans = ''
        for i in range(initnum):
            pro = progress(i, random.randint(0, a), random.randint(0, b), random.randint(0, c), random.randint(1, 5))
            redis.rpush("pro_ready", pickle.dumps(pro))
            ans += '初始化 ： ID：' + str(pro.id) + "    " + 'A :' + str(pro.a) + "    " + 'B :' + str(
                pro.b) + "    " + 'C :' + str(pro.c) + "    " + 'NEED TIME :' + str(pro.need_time) + '\n'
        response = HttpResponse(json.dumps({"ans": ans}))
        response["Access-Control-Allow-Origin"] = "*"
        return response


def progressgo(request):
    if request.method == 'POST':
        concat = request.POST
        time = int(concat["time"])
        try:
            nums = int(concat["allnum"])
            A = int(concat["a_num"])
            B = int(concat["b_num"])
            C = int(concat["c_num"])
        except:
            nums = 5
            A, B, C = 10, 10, 10
        t = 0
        info = '运行时初始化信息：\n'
        while t < time:
            for i in range(redis.llen("pro_ready")):  # 遍历一次 刷新状态
                a = int(redis.get("a"))
                b = int(redis.get("b"))
                c = int(redis.get("c"))
                pro = pickle.loads(redis.lindex("pro_ready", i))
                if pro.status == "W":
                    if pro.a <= a and pro.b <= b and pro.c <= c:
                        a -= pro.a
                        b -= pro.b
                        c -= pro.c
                        redis.set("a", a)
                        redis.set("b", b)
                        redis.set("c", c)
                        pro.status = "R"
                if pro.status == "R":
                    pro.get_time += 1
                    if pro.get_time == pro.need_time:
                        pro.status = "E"
                        a += pro.a
                        b += pro.b
                        c += pro.c
                        redis.set("a", a)
                        redis.set("b", b)
                        redis.set("c", c)
                redis.lset("pro_ready", i, pickle.dumps(pro))

            if random.randint(1, 5) == 3 and redis.llen("pro_ready") < nums:
                pro = progress(redis.llen("pro_ready"), random.randint(0, A), random.randint(0, B),
                               random.randint(0, C),
                               random.randint(1, 5))
                redis.rpush("pro_ready", pickle.dumps(pro))
                info += '初始化 ： ID：' + str(pro.id) + "    " + 'A :' + str(pro.a) + "    " + 'B :' + str(
                    pro.b) + "    " + 'C :' + str(pro.c) + "    " + 'NEED TIME :' + str(pro.need_time) +'    '+ '在时刻：' + str(t) + '\n'
            t += 1
        r_list = "运行队列： \n"
        w_list = "等待队列： \n"
        e_list = "结束队列:  \n"
        e = 0
        for i in range(redis.llen("pro_ready")):  # 遍历一次 记录结果
            pro = pickle.loads(redis.lindex("pro_ready", i))
            if pro.status == "W":
                w_list += 'ID：' + str(pro.id)+'    ' + 'NEED TIME :' + str(pro.need_time) + '\n'
            elif pro.status == "R":
                r_list += 'ID：' + str(pro.id)+'    ' + 'GET TIME :' + str(pro.get_time)+'    ' + 'NEED TIME :' + str(
                    pro.need_time) + '\n'
            elif pro.status == "E":
                e += 1
                e_list += 'ID：' + str(pro.id)+'    ' + "运行结束" + '\n'
        ans = info + r_list + w_list + e_list
        stop = False
        if e == nums:
            stop = True
        a = int(redis.get("a"))
        b = int(redis.get("b"))
        c = int(redis.get("c"))
        res = {"ans": ans,
               "stop": stop,
               "a": a/A * 100,
               "b": b/B * 100,
               "c": c/C * 100}
        response = HttpResponse(json.dumps(res))
        response["Access-Control-Allow-Origin"] = "*"
        return response
